//------------------------------------------------------------------------------
// <pcdd-entitiy>
//     代理业务类库
//     代理账号业务对象
// </pcdd-entitiy>
//------------------------------------------------------------------------------

using CL.Business.DAL;
using CL.Business.Entity;
using CL.Enum.Common;
using CL.Enum.Common.Type;
using CL.Enum.Common.Union;
using CL.Json.Entity.WebAPI;
using CL.Redis.BLL;
using CL.Tools.Common;
using CL.View.Entity.Business;
using System;
using System.Collections.Generic;

namespace CL.Business.BLL
{

    /// <summary>
    /// AccountBLL 业务
    /// </summary>
    public class AccountBLL
    {
        Log log = new Log("AccountBLL");
        AccountDAL dal = new AccountDAL(DbConnectionEnum.CaileBusiness);

        /// <summary>
        /// 根据用户名登录
        /// </summary>
        /// <param name="AccountCode"></param>
        /// <returns></returns>
        public AccountEntity QueryEntity(string AccountCode)
        {
            return dal.QueryEntity(AccountCode);
        }

        /// <summary>
        /// 查询用户对象
        /// </summary>
        /// <param name="AccountID"></param>
        /// <returns></returns>
        public AccountEntity QueryEntity(int AccountID)
        {
            return dal.QueryEntity(AccountID);
        }

        /// <summary>
        /// 根据身份证查询用户对象
        /// </summary>
        /// <param name="IdentityID"></param>
        /// <returns></returns>
        public AccountEntity QueryEntityByIdCard(string IdentityID)
        {
            return dal.QueryEntityByIdCard(IdentityID);
        }

        /// <summary>
        /// 根据手机号码查询用户
        /// </summary>
        /// <param name="phoneNum"></param>
        /// <returns></returns>
        public AccountEntity QueryEntityByMoblie(string phoneNum)
        {
            return dal.QueryEntityByMobile(phoneNum);
        }

        /// <summary>
        /// 根据银行卡查询用户对象
        /// </summary>
        /// <param name="AccountID"></param>
        /// <returns></returns>
        public AccountEntity QueryEntityByBankID(string bankId)
        {
            return dal.QueryEntityByBankID(bankId);
        }

        /// <summary>
        /// 更新密码
        /// </summary>
        /// <param name="AccountID"></param>
        /// <param name="AccountPwd"></param>
        /// <returns></returns>
        public bool ModifyEntity(int AccountID, string AccountPwd)
        {
            return dal.ModifyEntity(AccountID, AccountPwd);
        }

        /// <summary>
        /// 更新对象
        /// </summary>
        /// <param name="Entity"></param>
        /// <returns></returns>
        public int UpdateEntity(AccountEntity Entity)
        {
            return dal.Update(Entity);
        }

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DelEntity(int id)
        {
            return dal.DelEntity(id);
        }



        /// <summary>
        /// 修改用户状态
        /// </summary>
        /// <param name="AccountID"></param>
        /// <param name="iStatus"></param>
        /// <returns></returns>
        public bool AccountInfoAuditing(int AccountID,int iStatus)
        {
            bool flag = false;
            try
            {
                var accountInfo = new AccountBLL().QueryEntity(AccountID);
                accountInfo.AccountStatus = iStatus;
                if((int)AccountStatusEnum.noPass == iStatus)  //不通过清除图片路径, 用户重新上传
                {
                    accountInfo.FirstIdentityImage = "";
                    accountInfo.SecondIdentityImage = "";
                    accountInfo.BankCardImage = "";
                }
                UpdateEntity(accountInfo);                  
                flag = true;
            }
            catch (System.Exception)
            {
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 插入记录
        /// </summary>
        /// <param name="Entity"></param>
        /// <returns></returns>
        public int InsertEntity(AccountEntity Entity)
        {
            return dal.InsertEntity(Entity);
        }

        /// <summary>
        /// 从内存中取得所有下级类别列表（自身迭代）
        /// </summary>
        public List<udv_Account> GetChilds()
        {
            List<udv_Account> newData = new List<udv_Account>();
            foreach (var item in dal.QueryListByPage())
            {

                //添加一行数据
                udv_Account row = new udv_Account();
                row.AccountID = item.AccountID;
                row.AccountPwd = item.AccountPwd;
                row.AccountCode = item.AccountCode;
                row.BankCard = item.BankCard;
                row.FullName = item.FullName;
                row.AccountStatus = item.AccountStatus;
                row.CreateTime = item.CreateTime;
                row.IdentityID = item.IdentityID;
                row.Links = item.Links;
                newData.Add(row);
            }
            return newData;
        }

        public List<AccountEntity> QueryListByPage(string orderby, int pageIndex, int pageSize, string searchKey, ref int recordCount)
        {
            return dal.QueryListByPage(orderby,pageIndex,pageSize, searchKey, ref recordCount);
        }

        /// <summary>
        /// 代理查询
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public List<udv_Account> QueryAccountList(string UserName)
        {
            return dal.QueryAccountList(UserName);
        }

        /// <summary>
        /// 判断注册参数
        /// </summary>
        /// <param name="regEntity"></param>
        /// <returns></returns>
        protected int CheckParam(AccountEntity regEntity)
        {
            //检测用户是否注册过
            AccountEntity entity = new AccountBLL().QueryEntity(regEntity.AccountCode);
            if (entity != null)
            {
                return (int)ResultCode.UserAlreadyExist;
            }

            //检测手机是否注册过
            entity = new AccountBLL().QueryEntityByMoblie(regEntity.UserMobile);
            if (entity != null)
            {
                return (int)ResultCode.Mobiles;
            }

            //检测身份证是否注册过
            entity = new AccountBLL().QueryEntityByIdCard(regEntity.IdentityID);
            if (entity != null)
            {
                return (int)ResultCode.ExistIdentityID;
            }

            //检测银行卡号是否注册过
            entity = new AccountBLL().QueryEntityByBankID(regEntity.BankCard);
            if (entity != null)
            {
                return (int)ResultCode.IsBankCardExist;
            }
            return (int)ResultCode.Success;
    }

        /// <summary>
        /// 手机注册代理会员
        /// </summary>
        /// <param name="regEntity"></param>
        /// <param name="VerifyCode"></param>
        /// <returns></returns>
        public LoginResult MobileRegister(AccountEntity regEntity, string VerifyCode)
        {
            LoginResult result = null;
            try
            {
                int RecCode = CheckParam(regEntity);
                if((int)ResultCode.Success == RecCode)
                {
                    int VerifyResult = new SystemRedis().VerifyCodeRedis(regEntity.UserMobile, VerifyCode, (int)VerifyTypeEnum.Register);
                    if (VerifyResult == (int)ResultCode.Success) //验证码正确
                    {
                        regEntity.AccountPwd = EncryptAlgorithm.MD5(regEntity.AccountPwd);
                        regEntity.CreateTime = DateTime.Now;
                        long UserCode = this.InsertEntity(regEntity);
                        if (UserCode <= 0)
                        {
                            RecCode = (int)ResultCode.RegisterFailure;
                        }
                        else
                        {
                            RecCode = (int)ResultCode.Success;
                        }
                    }
                    else if (VerifyResult == 1)
                        RecCode = (int)ResultCode.CodeError;
                    else
                        RecCode = (int)ResultCode.CodeInvalidation;
                }

                result = new LoginResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                };
            }
            catch (Exception ex)
            {
                log.Write("手机号码注册错误[MobileRegister]：" + ex.StackTrace, true);
                result = new LoginResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy) + ex.Message
                };
            }
            return result;
        }

        protected int ChechParamFromForgetPassword(AccountEntity regEntity)
        {
            //检测用户是否注册过
            AccountEntity entity = new AccountBLL().QueryEntity(regEntity.AccountCode);
            if (entity == null)
            {
                return (int)ResultCode.UserNotExist;
            }

            if(entity.UserMobile != regEntity.UserMobile)
            {
                return (int)ResultCode.MobileDiffer;
            }

            return (int)ResultCode.Success;
        }

        /// <summary>
        /// 忘记密码, 重设密码
        /// </summary>
        /// <param name="regEntity"></param>
        /// <param name="VerifyCode"></param>
        /// <returns></returns>
        public LoginResult ForgetPassword(AccountEntity regEntity, string VerifyCode)
        {
            LoginResult result = null;
            try
            {
                int RecCode = ChechParamFromForgetPassword(regEntity);
                if ((int)ResultCode.Success == RecCode)
                {
                    int VerifyResult = new SystemRedis().VerifyCodeRedis(regEntity.UserMobile, VerifyCode, (int)VerifyTypeEnum.RetrievePwd);
                    if (VerifyResult == (int)ResultCode.Success) //验证码正确
                    {
                        string newPassword = regEntity.AccountPwd;
                        regEntity = QueryEntityByMoblie(regEntity.UserMobile);
                        regEntity.AccountPwd = EncryptAlgorithm.MD5(newPassword);
                        long UserCode = this.UpdateEntity(regEntity);
                        if (UserCode <= 0)
                        {
                            RecCode = (int)ResultCode.ChangePasswordFail;
                        }
                        else
                        {
                            RecCode = (int)ResultCode.Success;
                        }
                    }
                    else if (VerifyResult == 1)
                        RecCode = (int)ResultCode.CodeError;
                    else
                        RecCode = (int)ResultCode.CodeInvalidation;
                }

                result = new LoginResult()
                {
                    Code = RecCode,
                    Msg = Common.GetDescription((ResultCode)RecCode),
                };
            }
            catch (Exception ex)
            {
                log.Write("重置密码错误[ForgetPassword]：" + ex.StackTrace, true);
                result = new LoginResult()
                {
                    Code = (int)ResultCode.SystemBusy,
                    Msg = Common.GetDescription(ResultCode.SystemBusy) + ex.Message
                };
            }
            return result;
        }

    }
}
